package DBUtils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.apache.commons.dbutils.DbUtils;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
import java.util.ResourceBundle;

public class DBUtils {
    private static DataSource source;
    static {
        try{
            //创建properties对象，用来封装从文件中获取的流数据
            Properties pros = new Properties();
            //采用类加载方式获取文件的内容，并封装成流
            InputStream is = DbUtils.class.getResourceAsStream("/db.properties");
//            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("db.properties");
            //将流传入到pros对象中
            pros.load(is);
            //利用工厂类创建数据库连接池
            source = DruidDataSourceFactory.createDataSource(pros);
            System.out.println(source);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static Connection getConnByDruid() throws Exception {
        //所有的数据连接池要想被java所使用，都必须先实现sun公司提供的一个接口DateSource
        //获取数据库连接池对象
        Connection conn = source.getConnection();
        return conn;
    }


    //通过传统方法获取连接
    public static Connection getConn() throws ClassNotFoundException, SQLException {
        Connection conn = null;
        try {
            ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
            String driver = bundle.getString("driver");
            String user = bundle.getString("user");
            String url = bundle.getString("url");
            String password = bundle.getString("password");
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
        }catch (Exception e){
            e.printStackTrace();
        }
        return conn;
    }

    //关闭资源的文件
    public static void closeSource(Connection conn, Statement st, ResultSet res) {
        try{
            if (conn != null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        try{
            if (st != null){
                st.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        try{
            if (res != null){
                res.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    public static void closeSource(Connection conn, Statement st) {
        try{
            if (conn != null){
                conn.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        try{
            if (st != null){
                st.close();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
